<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;

class UserAccount extends Model
{
    public static function add($userId)
    {
        $row = self::get(['user_id' => $userId]);
        if(!$row) {
            return self::create(['user_id' => $userId, 'create_time' => time()]);
        } else {
            return $row;
        }
    }

    // 投票或拉票修改金额
    public function activityEdit($money, $getUser, $outUser, $is_vote = 1)
    {
        // 投票或分享会获得佣金，佣金在活动后会结束到余额
        $getUser->brokerage = $getUser->brokerage + $money;
        $getUser->del_amount = $getUser->add_amount + $money;
        $getUser->save();

        // 获取
        $data[0] = [
            'user_id' => $getUser->user_id,
            'change'  => $money,
            'balance' => $getUser->balance,
            'type' => $is_vote ? 4 : 5,
            'create_time' => time(),
        ];
        // 付出
        // $outUser = self::get(['user_id' => $outUserId]);
        $outUser->balance = $outUser->balance - $money;
        $outUser->del_amount = $outUser->del_amount + $money;
        $outUser->save();
        $data[1] = [
            'user_id' => $outUser->user_id,
            'change'  => - $money,
            'balance' => $outUser->balance,
            'type' => $is_vote ? 2 : 3,
            'create_time' => time(),
        ];
        return (new UserAccountRecord())->insertAll($data);
    }
}
